package com.lanren.common.base.impl;

import android.os.Bundle;

import com.lanren.common.base.IPresenter;
import com.lanren.common.utils.LogUtils;

/**
 * @ClassName BaseLazyFragment
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2019/10/5 15:58
 * @Version 1.0
 */
public abstract class BaseLazyFragment<P extends IPresenter> extends BaseFragment<P> {

    // 是否进行过懒加载
    private boolean isLazyLoad;
    // Fragment 是否可见
    private boolean isFragmentVisible;
    // 是否是 replace Fragment 的形式
    private boolean isReplaceFragment;

    private Bundle state;

    public Bundle getState() {
        return state;
    }

    /**
     * 是否进行了懒加载
     */
    protected boolean isLazyLoad() {
        return isLazyLoad;
    }

    /**
     * 当前 Fragment 是否可见
     */
    public boolean isFragmentVisible() {
        return isFragmentVisible;
    }

    @Override
    public void doCreateView(Bundle state) {
        if (isReplaceFragment) {
            if (isFragmentVisible) {
                initLazyLoad();
            }
        } else {
            initLazyLoad();
        }
    }

    /**
     * 初始化懒加载
     */
    protected void initLazyLoad() {
        LogUtils.d("initLazyLoad =" + isReplaceFragment + "  " + isFragmentVisible + "  " + isLazyLoad + "  " + this.getClass()
                .getSimpleName());
        if (!isLazyLoad) {
            isLazyLoad = true;
            initFragment();
        }
    }


    // replace Fragment时使用，ViewPager 切换时会回调此方法
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isReplaceFragment = true;
        this.isFragmentVisible = isVisibleToUser;
        if (isVisibleToUser && getParentView() != null) {
            if (!isLazyLoad) {
                initLazyLoad();
            } else {
                // 从不可见到可见
                onRestart();
            }
        }
    }

    protected abstract void initFragment();

    /**
     * 从可见的状态变成不可见状态，再从不可见状态变成可见状态时回调
     */
    protected abstract void onRestart();
}
